<?php

class League extends DataObject {
	static $db = array(
		"Name" => "Varchar(255)"
		);

		static $many_many = array(
		"Teams" => 'Team',
	    "Points" => 'TeamPoint'
	    );

	    static $has_one = array (
		"Season" => "Season"
		);

		static $default_sort = 'Name DESC';

		public $Round = 1;
		public $tempResult;

		public function TeamTable() {
			return $this->renderWith('LeagueEditor_teamtable');
		}
		public function GameTable() {
			return $this->renderWith('GameEditor_gametable');
		}

		public function Games() {
			$res = DataObject::get('Game','`Game`.round = '.$this->Round.' AND `Game`.LeagueID = ' . $this->ID);
			return $res;
		}

		public function AllTeams() {
			$set = DataObject::get('Team','','Title');
			return $set;

		}

		public function PrevRound() {
			return $this->Round -1;
		}

		public function NextRound() {
			$res = DB::query('SELECT Max(round) From Game WHERE LeagueID = ' . $this->ID);
			$row = $res->nextRecord();
			if ($this->Round >= $row['Max(round)'])
			return 0;
			else
			return $this->Round +1;
		}

		public function Teams() {
			$teams = parent::Teams();
			foreach ($teams AS $team) {
				$team->ParentLeague = $this;
			}
			return $teams;
		}

		private function fillTeamPoint($games,$result) {
			$data = array();
			
			$data['PlayedGames'] = ($games)?$games->Count():0;
			$data['GoalsShot'] = 0;
			$data['GoalsRecieved'] = 0;
			$data['Wins'] = 0;
			$data['Draws'] = 0;
			$data['Defeats'] = 0;
			$data['Points'] = 0;
			$data['FairplayPoints'] = 0;
			$data['FairPlayFoulPoints'] = 0;
			
			$data['FoulPoints'] = 0;
			$lId = $this->ID;
			if ($games) {
				foreach ($games AS $game) {
					$s = 0;
					$r = 0;
					if ($lId < 0)$lId = $game->LeagueID;
					if ($game->HomeTeamID == $result->TeamID) {
						$data['GoalsShot'] += $game->GoalsHomeTeam;
						$data['GoalsRecieved'] += $game->GoalsGuestTeam;
						$s = $game->GoalsHomeTeam;
						$r = $game->GoalsGuestTeam;
						$data['FairplayPoints'] += $game->FPHome;
					} else {
						$data['GoalsShot'] += $game->GoalsGuestTeam;
						$data['GoalsRecieved'] += $game->GoalsHomeTeam;
						$s = $game->GoalsGuestTeam;
						$r = $game->GoalsHomeTeam;
						$data['FairplayPoints'] += $game->FPGuest;
					}
					if ($s > $r)
					$data['Wins']++;
					else if ($r > $s)
					$data['Defeats']++;
					else
					$data['Draws']++;
				}
			}
			$data['Points'] += $data['Wins'] * 3;
			$data['Points'] += $data['Draws'];
			$fps = DataObject::get('FoulPoint','TeamID = ' . $result->TeamID . " AND LeagueID = ".$lId);
			if ($fps) {
				foreach ($fps AS $fp) {
					$data['FoulPoints'] += intval($fp->points);
				}
			}
			$data['Points'] -= $data['FoulPoints'];
			
		    $fps = DataObject::get('FairPlayFoulPoint','TeamID = ' . $result->TeamID . " AND LeagueID = ".$lId);
            if ($fps) {
                foreach ($fps AS $fp) {
                    $data['FairPlayFoulPoints'] += intval($fp->points);
                }
            }
			$data['FairplayPoints'] -= $data['FairPlayFoulPoints'];

			foreach ($data AS $key=>$val) {
				$result->$key = $val;
			}

			return $result;
		}

		private function swap($index,$index2,$array) {

			$temp = $array[$index];
			$array[$index] = $array[$index2];
			$array[$index2] = $temp;
			return $array;

		}

		private function sortByRank($tableData) {
			$n = sizeof($tableData);

			$swapped = true;
			while($swapped) {
				$swapped = false;
				for ($i =0;$i < ($n - 1); $i++) {
					if ($tableData[$i]->Points < $tableData[$i + 1]->Points ) {

						$tableData = $this->swap($i,($i + 1),$tableData);
						$swapped = true;
				    } else if ($tableData[$i]->Points == $tableData[$i + 1]->Points) {
				    	$diff = $tableData[$i]->GoalsShot - $tableData[$i]->GoalsRecieved;
                        $diff2 = $tableData[$i + 1]->GoalsShot - $tableData[$i + 1]->GoalsRecieved;
                        //Primary is Fairplay points
                        if ($tableData[$i]->FairplayPoints < $tableData[$i + 1]->FairplayPoints) {   
                            $tableData = $this->swap($i,($i + 1),$tableData);
                            $swapped = true;
                        //second goal difference
                        } else if ($diff < $diff2 || ($diff == $diff2 && $tableData[$i]->GoalsShot < $tableData[$i + 1]->GoalsShot)) {
							$tableData = $this->swap($i,($i + 1),$tableData);
							$swapped = true;
						}
					}
				}
				$n--;
			}
			return $tableData;
		}

		public function updateTable() {
			$table = $this->obj('Points');
			$teams = $this->obj('Teams');
			$tableData = array();
			foreach ($teams AS $team) {
				$result = false;
				if ($table)
				    $result = DataObject::get_one('TeamPoint','TeamID = ' .$team->ID . ' AND LeagueID = ' .$this->ID);
				if (!$result) {
					$result = new TeamPoint();
					$result->TeamID = $team->ID;
					$result->LeagueID = $this->ID;
					$result->write();
					//$table->add($result);
					DB::query('INSERT INTO League_Table (LeagueID,TeamPointID) VALUES('.$this->ID.','.$result->ID.')');
				}
				$games = DataObject::get('Game','
				    (HomeTeamID = ' .$team->ID. ' OR GuestTeamID = ' . $team->ID . ') 
				    AND leagueID =' .$this->ID . ' AND GoalsHomeTeam > -1 AND GoalsGuestTeam > -1');

			
				$tableData[] = $this->fillTeamPoint($games,$result);
				
			}

			$tableData = $this->sortByRank($tableData);

			for ($i=0;$i < sizeof($tableData);$i++) {
				$tableData[$i]->Rank = ($i + 1);
				$tableData[$i]->write();
			}
		}

		public function Table() {
			$table = DataObject::get('TeamPoint','LeagueID = ' . $this->ID,'Rank');
			return $table;
		}
		public function TableResults() {
			return $this->renderWith('Season_tableResults');
		}
		
		public function LastGames() {
			$result = DB::query('SELECT Round FROM Game WHERE GoalsHomeTeam > -1 AND GoalsGuestTeam > -1 AND LeagueID = ' . $this->ID . ' ORDER BY Round DESC LIMIT 1');
			//$result = new Query();
			$row = $result->record();
			if (!$row['Round'])
			return null; 
			$ret = DataObject::get('Game','LeagueID = ' . $this->ID . ' AND Round='.$row['Round'],'GameDate,GameTime');
            return $ret;
		}
		
        public function NextGames() {
            $result = DB::query('SELECT Round FROM Game WHERE GoalsHomeTeam < 0 AND GoalsGuestTeam < 0 AND LeagueID = ' . $this->ID . ' ORDER BY Round LIMIT 1');
            //$result = new Query();
            $row = $result->record();
            $ret = DataObject::get('Game','LeagueID = ' . $this->ID . ' AND Round='.$row['Round'],'GameDate,GameTime');
            return $ret;
        }
        
        public function AllGames() {
        	/*
        	$result = DB::query('SELECT Round FROM Game WHERE LeagueID = ' . $this->ID . ' ORDER BY Round DESC LIMIT 1');
        	$row = $result->record();
        	$ret = new DataObjectSet();
        	for ($i =1; $i <=intval($row['Round']);$i++) {
        		$ret->push($this->RoundGames($i));
        	}
        	var_dump($ret);
        	die();
        	*/
        	$ret = DataObject::get('Game','LeagueID = ' . $this->ID,'Round,GameDate,GameTime');
        	$lastRound = 1;
        	foreach ($ret AS $game) {
        		if ($lastRound != $game->Round)
        		{
        			$game->NewRound = true;
        			$lastRound = $game->Round;
        		}
        		
        	}
            return $ret;
        }
        
        public function RoundGames($round) {
        	$ret = DataObject::get('Game','LeagueID = ' . $this->ID . ' AND Round='.$round,'GameDate,GameTime');
        }
        
        public function Schedule() {
            return $this->renderWith('Season_schedule');
        }

}

?>